from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QMessageBox

from src.main.server.controller.login_controller import LoginController


class RegisterUiLoader:
    def __init__(self, controller=None):
        self.ui_file_path = "../../../qt_ui/register.ui"
        self.window = None
        self.controller = controller
        self._load_ui()

    def _load_ui(self):
        file = QFile(self.ui_file_path)
        try:
            self.window = QUiLoader().load(file)
            self.window.pushButton.clicked.connect(self.show_confirmation_dialog)
            self.window.pushButton_2.clicked.connect(self.clear)
            self.window.pushButton_3.clicked.connect(self.checkout_login_window)

            # 性别按钮组
            self.window.buttonGroup.buttonClicked.connect(self.handle_gender_selection)
        finally:
            file.close()

    def checkout_login_window(self):
        print("进入登录UI")
        self.window.close()
        if self.controller:
            self.controller.show_login()

    def clear(self):
        print("清除表单数据")
        self.window.lineEdit.clear()        # 用户名
        self.window.lineEdit_5.clear()      # 密码
        self.window.lineEdit_2.clear()      # 年龄
        self.window.lineEdit_3.clear()      # 联系方式
        self.window.lineEdit_4.clear()      # 邮箱地址

    def handle_gender_selection(self):
        """按钮组的动态获取"""
        selected_button = self.window.buttonGroup.checkedButton()
        if selected_button:
            self.gender = selected_button.text()
        else:
            self.gender = None

    def register_check(self):
        """注册检查"""
        self.handle_gender_selection()
        username = self.window.lineEdit.text()
        password = self.window.lineEdit_5.text()
        age = self.window.lineEdit_2.text()
        gender = self.gender
        pho_num = self.window.lineEdit_3.text()
        email = self.window.lineEdit_4.text()


        if username and password and gender and age and pho_num:
            LoginController().register(username,
                                       password,
                                       age,
                                       gender,
                                       pho_num,
                                       email
                                       )
            print("注册成功,将自动跳转到登录界面")
            self.checkout_login_window()
        else:
            print("你有未填写的表单信息")


    def show_confirmation_dialog(self):
        # 使用 self.window 作为父级窗口
        reply = QMessageBox.question(
            self.window,
            "确认",
            "是否确定执行此操作？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            print("用户选择继续注册")
            self.register_check()
        else:
            print("用户取消注册")

